import 'package:flutter/material.dart';
import 'package:math_expressions/math_expressions.dart';
import 'package:window_manager/window_manager.dart';
import 'dart:async';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();

  try {
    await windowManager.ensureInitialized();

    WindowOptions windowOptions = WindowOptions(
      size: Size(452, 910),
      center: true,
      title: "计算器",
      backgroundColor: Colors.transparent,
      skipTaskbar: false,
      titleBarStyle: TitleBarStyle.normal,
    );

    await windowManager.waitUntilReadyToShow(windowOptions, () async {
      await windowManager.show();
      await windowManager.focus();
    });
  } catch (e) {
    print('窗口管理初始化失败: $e');
  }

  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: '计算器',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
      ),
      home: Home(),
    );
  }
}

class Home extends StatefulWidget {
  const Home({super.key});

  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> with TickerProviderStateMixin {
  late AnimationController _cursorController;
  late Animation<double> _cursorAnimation;
  String A = "";

  @override
  void initState() {
    super.initState();

    _cursorController = AnimationController(
      duration: Duration(milliseconds: 500),
      vsync: this,
    );

    _cursorAnimation = Tween<double>(begin: 0.0, end: 1.5).animate(
      CurvedAnimation(parent: _cursorController, curve: Curves.easeInOut),
    );

    _cursorController.repeat(reverse: true);
  }

  @override
  void dispose() {
    _cursorController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ListView(
        children: [
          SizedBox(
            height: 370,
            width: double.infinity,
            child: Stack(
              alignment: Alignment.centerRight,
              children: [
                Padding(
                  padding: EdgeInsets.only(right: 20),
                  child: Text(A, style: TextStyle(fontSize: 75)),
                ),
                Positioned(
                  right: 0,
                  child: FadeTransition(
                    opacity: _cursorAnimation,
                    child: Text(
                      'l',
                      style: TextStyle(
                        fontSize: 75,
                        color: Colors.blue,
                        fontWeight: FontWeight.w100,
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),

          Row(
            children: [
              SizedBox(width: 20),
              ElevatedButton(
                onPressed: () {
                  setState(() {
                    A = "";
                  });
                },
                style: ButtonStyle(
                  fixedSize: WidgetStateProperty.all(Size(80, 80)),
                ),
                child: Text("C", style: TextStyle(fontSize: 30)),
              ),
              SizedBox(width: 20),
              ElevatedButton(
                onPressed: () {
                  setState(() {
                    if (A.isNotEmpty) {
                      A += "/";
                    }
                  });
                },
                style: ButtonStyle(
                  fixedSize: WidgetStateProperty.all(Size(80, 80)),
                ),
                child: Text("/", style: TextStyle(fontSize: 30)),
              ),
              SizedBox(width: 20),
              ElevatedButton(
                onPressed: () {
                  setState(() {
                    if (A.isNotEmpty) {
                      A += "X";
                    }
                  });
                },
                style: ButtonStyle(
                  fixedSize: WidgetStateProperty.all(Size(80, 80)),
                ),
                child: Text("X", style: TextStyle(fontSize: 30)),
              ),
              SizedBox(width: 20),
              ElevatedButton(
                onPressed: () {
                  setState(() {
                    if (A.isNotEmpty) {
                      A = A.substring(0, A.length - 1);
                    }
                  });
                },
                style: ButtonStyle(
                  fixedSize: WidgetStateProperty.all(Size(80, 80)),
                ),
                child: Icon(Icons.backspace_outlined, size: 30),
              ),
            ],
          ),
          SizedBox(height: 20),
          Row(
            children: [
              SizedBox(width: 20),
              ElevatedButton(
                onPressed: () {
                  setState(() {
                    A += "7";
                  });
                },
                style: ButtonStyle(
                  fixedSize: WidgetStateProperty.all(Size(80, 80)),
                ),
                child: Text("7", style: TextStyle(fontSize: 30)),
              ),
              SizedBox(width: 20),
              ElevatedButton(
                onPressed: () {
                  setState(() {
                    A += "8";
                  });
                },
                style: ButtonStyle(
                  fixedSize: WidgetStateProperty.all(Size(80, 80)),
                ),
                child: Text("8", style: TextStyle(fontSize: 30)),
              ),
              SizedBox(width: 20),
              ElevatedButton(
                onPressed: () {
                  setState(() {
                    A += "9";
                  });
                },
                style: ButtonStyle(
                  fixedSize: WidgetStateProperty.all(Size(80, 80)),
                ),
                child: Text("9", style: TextStyle(fontSize: 30)),
              ),
              SizedBox(width: 20),
              ElevatedButton(
                onPressed: () {
                  setState(() {
                    if (A.isNotEmpty) {
                      A += "—";
                    }
                  });
                },
                style: ButtonStyle(
                  fixedSize: WidgetStateProperty.all(Size(80, 80)),
                ),
                child: Text("—", style: TextStyle(fontSize: 30)),
              ),
            ],
          ),
          SizedBox(height: 20),
          Row(
            children: [
              SizedBox(width: 20),
              ElevatedButton(
                onPressed: () {
                  setState(() {
                    A += "4";
                  });
                },
                style: ButtonStyle(
                  fixedSize: WidgetStateProperty.all(Size(80, 80)),
                ),
                child: Text("4", style: TextStyle(fontSize: 30)),
              ),
              SizedBox(width: 20),
              ElevatedButton(
                onPressed: () {
                  setState(() {
                    A += "5";
                  });
                },
                style: ButtonStyle(
                  fixedSize: WidgetStateProperty.all(Size(80, 80)),
                ),
                child: Text("5", style: TextStyle(fontSize: 30)),
              ),
              SizedBox(width: 20),
              ElevatedButton(
                onPressed: () {
                  setState(() {
                    A += "6";
                  });
                },
                style: ButtonStyle(
                  fixedSize: WidgetStateProperty.all(Size(80, 80)),
                ),
                child: Text("6", style: TextStyle(fontSize: 30)),
              ),
              SizedBox(width: 20),
              ElevatedButton(
                onPressed: () {
                  setState(() {
                    if (A.isNotEmpty) {
                      A += "+";
                    }
                  });
                },
                style: ButtonStyle(
                  fixedSize: WidgetStateProperty.all(Size(80, 80)),
                ),
                child: Text("+", style: TextStyle(fontSize: 30)),
              ),
            ],
          ),
          SizedBox(height: 20),
          Row(
            children: [
              SizedBox(width: 20),
              ElevatedButton(
                onPressed: () {
                  setState(() {
                    A += "1";
                  });
                },
                style: ButtonStyle(
                  fixedSize: WidgetStateProperty.all(Size(80, 80)),
                ),
                child: Text("1", style: TextStyle(fontSize: 30)),
              ),
              SizedBox(width: 20),
              ElevatedButton(
                onPressed: () {
                  setState(() {
                    A += "2";
                  });
                },
                style: ButtonStyle(
                  fixedSize: WidgetStateProperty.all(Size(80, 80)),
                ),
                child: Text("2", style: TextStyle(fontSize: 30)),
              ),
              SizedBox(width: 20),
              ElevatedButton(
                onPressed: () {
                  setState(() {
                    A += "3";
                  });
                },
                style: ButtonStyle(
                  fixedSize: WidgetStateProperty.all(Size(80, 80)),
                ),
                child: Text("3", style: TextStyle(fontSize: 30)),
              ),
            ],
          ),
          SizedBox(height: 20),
          Row(
            children: [
              Center(
                child: Row(
                  children: [
                    SizedBox(width: 70),
                    ElevatedButton(
                      onPressed: () {
                        setState(() {
                          if (A != "0") {
                            A += "0";
                          }
                        });
                      },
                      style: ButtonStyle(
                        fixedSize: WidgetStateProperty.all(Size(80, 80)),
                      ),
                      child: Text("0", style: TextStyle(fontSize: 30)),
                    ),
                    SizedBox(width: 20),

                    ElevatedButton(
                      onPressed: () {
                        setState(() {
                          if (A.isNotEmpty) {
                            A += ".";
                          }
                        });
                      },
                      style: ButtonStyle(
                        fixedSize: WidgetStateProperty.all(Size(80, 80)),
                      ),
                      child: Text(".", style: TextStyle(fontSize: 30)),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ],
      ),
      floatingActionButton: ElevatedButton(
        onPressed: () {
          setState(() {
            double result = calculateExpression(A);
            if (!result.isNaN) {
              if (result % 1 == 0) {
                A = result.truncate().toString();
              } else {
                A = result.toString();
              }
            } else {
              A = "Error";
            }
          });
        },
        style: ButtonStyle(
          fixedSize: WidgetStateProperty.all(Size(100, 200)),
          shape: WidgetStateProperty.all<RoundedRectangleBorder>(
            RoundedRectangleBorder(borderRadius: BorderRadius.circular(30)),
          ),
        ),
        child: Text("=", style: TextStyle(fontSize: 30)),
      ),
    );
  }
}

double calculateExpression(String expression) {
  expression = expression.replaceAll('X', '*').replaceAll('—', '-');

  try {
    Parser p = Parser();
    Expression exp = p.parse(expression);
    ContextModel cm = ContextModel();
    double result = exp.evaluate(EvaluationType.REAL, cm);
    return result;
  } catch (e) {
    return double.nan;
  }
}
